Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Install Datasets and Upgrade TensorFlow

To ensure we can download the latest version of the oxford_flowers102 dataset, let's first install both tensorflow-datasets and tfds-nightly.

  • tensorflow-datasets is the stable version that is released on a cadence of every few months
  • tfds-nightly is released every day and has the latest version of the datasets

We'll also upgrade TensorFlow to ensure we have a version that is compatible with the latest version of the dataset.

In [1]:
%pip --no-cache-dir install tensorflow-datasets --user
%pip --no-cache-dir install tfds-nightly --user
%pip --no-cache-dir install --upgrade tensorflow --user
Requirement already satisfied: tensorflow-datasets in /opt/conda/lib/python3.7/site-packages (1.2.0)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.22.0)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.1.0)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.3.1.1)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.2.1)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.17.4)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.18.2)
Requirement already satisfied: psutil in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (5.6.7)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.14.0)
Requirement already satisfied: wrapt in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.11.2)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.8.1)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (4.36.1)
Requirement already satisfied: protobuf>=3.6.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (3.11.2)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.12.0)
Requirement already satisfied: attrs in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (19.3.0)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2019.11.28)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (1.24.2)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2.8)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tensorflow-datasets) (1.6.0)
Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from protobuf>=3.6.1->tensorflow-datasets) (41.4.0)
Note: you may need to restart the kernel to use updated packages.
Collecting tfds-nightly
  Downloading https://files.pythonhosted.org/packages/43/cb/2522bea938a2958016a2b09b2818a3c7c77ea7bf0eb8a7162e805c0c86a0/tfds_nightly-4.6.0.dev202207030045-py3-none-any.whl (4.4MB)
     |████████████████████████████████| 4.4MB 4.5MB/s eta 0:00:01     |████████▎                       | 1.1MB 4.5MB/s eta 0:00:01     |██████████████                  | 1.9MB 4.5MB/s eta 0:00:01
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Collecting etils[epath]
  Downloading https://files.pythonhosted.org/packages/6b/f0/d717858522d20a4493ea93368a6a737ac7db791e199b07524a41982053f7/etils-0.6.0-py3-none-any.whl (98kB)
     |████████████████████████████████| 102kB 13.2MB/s ta 0:00:01
Collecting toml
  Downloading https://files.pythonhosted.org/packages/44/6f/7120676b6d73228c96e17f1f794d8ab046fc910d781c8d151120c3f1569e/toml-0.10.2-py2.py3-none-any.whl
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Collecting protobuf>=3.12.2
  Downloading https://files.pythonhosted.org/packages/a3/43/c44402da90bf9c2c8f9fe70cc44c66b67cf94ca8e2fadaa0a46a9c6304d3/protobuf-4.21.2-cp37-abi3-manylinux2014_x86_64.whl (407kB)
     |████████████████████████████████| 409kB 11.5MB/s eta 0:00:01     |█████████████████████████████   | 368kB 11.5MB/s eta 0:00:01
Collecting importlib-resources; python_version < "3.9"
  Downloading https://files.pythonhosted.org/packages/3c/a7/4e4a2176fed10ab233cc39b083ba4ec222ba52de2be606e3e2b5195264e9/importlib_resources-5.8.0-py3-none-any.whl
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Collecting typing-extensions; python_version < "3.8"
  Downloading https://files.pythonhosted.org/packages/ed/d6/2afc375a8d55b8be879d6b4986d4f69f01115e795e36827fd3a40166028b/typing_extensions-4.3.0-py3-none-any.whl
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Requirement already satisfied: zipp; extra == "epath" in /opt/conda/lib/python3.7/site-packages (from etils[epath]->tfds-nightly) (0.6.0)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: more-itertools in /opt/conda/lib/python3.7/site-packages (from zipp; extra == "epath"->etils[epath]->tfds-nightly) (8.0.2)
ERROR: tensorflow-metadata 0.14.0 has requirement protobuf<4,>=3.7, but you'll have protobuf 4.21.2 which is incompatible.
ERROR: importlib-resources 5.8.0 has requirement zipp>=3.1.0; python_version < "3.10", but you'll have zipp 0.6.0 which is incompatible.
Installing collected packages: importlib-resources, etils, toml, protobuf, typing-extensions, tfds-nightly
  WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed etils-0.6.0 importlib-resources-5.8.0 protobuf-4.21.2 tfds-nightly-4.6.0.dev202207030045 toml-0.10.2 typing-extensions-4.3.0
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow
  Downloading https://files.pythonhosted.org/packages/db/27/6754ced3dfcdc0507c24df31b5daa9acfa6357f083b355081781fa040404/tensorflow-2.9.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (511.7MB)
     |██████████████▍                 | 229.9MB 5.0MB/s eta 0:00:571  |▏                               | 2.6MB 5.0MB/s eta 0:01:42     |▏                               | 3.3MB 5.0MB/s eta 0:01:41     |▍                               | 5.8MB 5.0MB/s eta 0:01:41     |▍                               | 6.6MB 5.0MB/s eta 0:01:41     |▊                               | 11.6MB 5.0MB/s eta 0:01:40     |█                               | 14.8MB 5.0MB/s eta 0:01:39     |█                               | 15.5MB 9.5MB/s eta 0:00:53     |█                               | 16.9MB 9.5MB/s eta 0:00:52     |█                               | 17.6MB 9.5MB/s eta 0:00:52     |█▏                              | 18.3MB 9.5MB/s eta 0:00:52     |█▌                              | 24.7MB 9.5MB/s eta 0:00:52     |█▉                              | 29.3MB 14.6MB/s eta 0:00:34     |██                              | 31.7MB 14.6MB/s eta 0:00:33     |██▏                             | 34.3MB 14.6MB/s eta 0:00:33     |██▎                             | 36.8MB 14.6MB/s eta 0:00:33     |██▌                             | 39.8MB 14.6MB/s eta 0:00:33     |██▊                             | 43.8MB 12.6MB/s eta 0:00:38     |██▉                             | 45.9MB 12.6MB/s eta 0:00:37     |███                             | 46.5MB 12.6MB/s eta 0:00:37     |███                             | 46.8MB 12.6MB/s eta 0:00:37     |███                             | 49.4MB 12.6MB/s eta 0:00:37     |███▎                            | 51.7MB 12.6MB/s eta 0:00:37     |███▎                            | 52.4MB 12.6MB/s eta 0:00:37     |███▍                            | 53.8MB 7.3MB/s eta 0:01:03     |███▌                            | 55.8MB 7.3MB/s eta 0:01:03     |███▊                            | 59.3MB 7.3MB/s eta 0:01:03     |███▊                            | 60.0MB 7.3MB/s eta 0:01:03     |███▉                            | 60.6MB 7.3MB/s eta 0:01:02     |███▉                            | 61.9MB 7.3MB/s eta 0:01:02     |████                            | 63.9MB 7.3MB/s eta 0:01:02     |████                            | 65.1MB 14.6MB/s eta 0:00:31     |████▏                           | 65.8MB 14.6MB/s eta 0:00:31     |████▏                           | 66.5MB 14.6MB/s eta 0:00:31     |████▏                           | 67.1MB 14.6MB/s eta 0:00:31     |████▋                           | 73.5MB 14.6MB/s eta 0:00:31     |████▊                           | 75.4MB 14.6MB/s eta 0:00:30     |████▉                           | 76.9MB 14.6MB/s eta 0:00:30     |█████                           | 78.9MB 10.8MB/s eta 0:00:41     |█████                           | 80.1MB 10.8MB/s eta 0:00:41     |█████                           | 81.4MB 10.8MB/s eta 0:00:40     |█████▏                          | 82.1MB 10.8MB/s eta 0:00:40     |█████▎                          | 84.0MB 10.8MB/s eta 0:00:40     |█████▎                          | 84.6MB 10.8MB/s eta 0:00:40     |█████▍                          | 85.3MB 10.8MB/s eta 0:00:40     |█████▌                          | 87.9MB 10.8MB/s eta 0:00:40     |█████▋                          | 89.2MB 5.3MB/s eta 0:01:20     |█████▋                          | 90.0MB 5.3MB/s eta 0:01:20     |█████▊                          | 91.3MB 5.3MB/s eta 0:01:20     |█████▊                          | 92.0MB 5.3MB/s eta 0:01:19     |█████▉                          | 93.3MB 5.3MB/s eta 0:01:19     |█████▉                          | 94.0MB 5.3MB/s eta 0:01:19     |██████                          | 97.5MB 5.3MB/s eta 0:01:18     |██████▏                         | 98.2MB 5.3MB/s eta 0:01:18     |██████▎                         | 100.4MB 5.3MB/s eta 0:01:18     |██████▎                         | 101.2MB 5.3MB/s eta 0:01:18     |██████▍                         | 101.9MB 6.5MB/s eta 0:01:04     |██████▌                         | 103.4MB 6.5MB/s eta 0:01:04     |██████▊                         | 108.3MB 6.5MB/s eta 0:01:03     |██████▉                         | 109.6MB 6.5MB/s eta 0:01:03     |███████                         | 110.3MB 6.5MB/s eta 0:01:03     |███████                         | 110.9MB 6.5MB/s eta 0:01:03     |███████▏                        | 114.4MB 7.2MB/s eta 0:00:56     |███████▏                        | 115.2MB 7.2MB/s eta 0:00:56     |███████▎                        | 116.0MB 7.2MB/s eta 0:00:56     |████████                        | 126.3MB 7.2MB/s eta 0:00:54     |████████                        | 129.0MB 5.3MB/s eta 0:01:13     |████████                        | 129.7MB 5.3MB/s eta 0:01:13     |████████▏                       | 130.4MB 5.3MB/s eta 0:01:13     |████████▍                       | 134.7MB 5.3MB/s eta 0:01:12     |████████▉                       | 141.0MB 7.2MB/s eta 0:00:52     |█████████                       | 142.2MB 7.2MB/s eta 0:00:52     |█████████                       | 142.8MB 7.2MB/s eta 0:00:52     |█████████▏                      | 147.4MB 7.2MB/s eta 0:00:51     |█████████▊                      | 154.7MB 12.9MB/s eta 0:00:28     |█████████▊                      | 156.2MB 12.9MB/s eta 0:00:28     |█████████▉                      | 157.5MB 12.9MB/s eta 0:00:28     |█████████▉                      | 158.1MB 12.9MB/s eta 0:00:28     |██████████                      | 158.7MB 12.9MB/s eta 0:00:28     |██████████                      | 160.5MB 12.9MB/s eta 0:00:28     |██████████                      | 161.1MB 12.9MB/s eta 0:00:28     |██████████▏                     | 162.4MB 12.9MB/s eta 0:00:28     |██████████▏                     | 162.9MB 12.9MB/s eta 0:00:28     |██████████▎                     | 163.6MB 28.9MB/s eta 0:00:13     |██████████▎                     | 164.2MB 28.9MB/s eta 0:00:13     |██████████▍                     | 165.5MB 28.9MB/s eta 0:00:12     |██████████▍                     | 166.3MB 28.9MB/s eta 0:00:12     |██████████▌                     | 168.2MB 28.9MB/s eta 0:00:12     |██████████▋                     | 168.9MB 28.9MB/s eta 0:00:12     |██████████▊                     | 171.0MB 28.9MB/s eta 0:00:12     |███████████                     | 174.9MB 28.9MB/s eta 0:00:12     |███████████                     | 176.3MB 13.8MB/s eta 0:00:25     |███████████                     | 177.6MB 13.8MB/s eta 0:00:25     |███████████▏                    | 178.3MB 13.8MB/s eta 0:00:25     |███████████▎                    | 179.7MB 13.8MB/s eta 0:00:24     |███████████▎                    | 180.4MB 13.8MB/s eta 0:00:24     |███████████▍                    | 181.5MB 13.8MB/s eta 0:00:24     |███████████▌                    | 183.3MB 13.8MB/s eta 0:00:24     |███████████▋                    | 186.6MB 13.8MB/s eta 0:00:24     |███████████▊                    | 187.2MB 24.1MB/s eta 0:00:14     |███████████▉                    | 189.3MB 24.1MB/s eta 0:00:14     |████████████                    | 191.3MB 24.1MB/s eta 0:00:14     |████████████                    | 191.9MB 24.1MB/s eta 0:00:14     |████████████                    | 192.6MB 24.1MB/s eta 0:00:14     |████████████▎                   | 196.4MB 24.1MB/s eta 0:00:14     |████████████▍                   | 198.3MB 13.3MB/s eta 0:00:24     |████████████▍                   | 199.0MB 13.3MB/s eta 0:00:24     |████████████▊                   | 202.9MB 13.3MB/s eta 0:00:24     |████████████▉                   | 204.7MB 13.3MB/s eta 0:00:24     |█████████████                   | 208.2MB 13.3MB/s eta 0:00:23     |█████████████                   | 208.8MB 13.3MB/s eta 0:00:23     |█████████████                   | 209.5MB 13.9MB/s eta 0:00:22     |█████████████▏                  | 210.1MB 13.9MB/s eta 0:00:22     |█████████████▎                  | 211.9MB 13.9MB/s eta 0:00:22     |█████████████▎                  | 213.2MB 13.9MB/s eta 0:00:22     |█████████████▍                  | 214.5MB 13.9MB/s eta 0:00:22     |█████████████▊                  | 219.0MB 13.9MB/s eta 0:00:22     |██████████████                  | 223.3MB 5.0MB/s eta 0:00:58     |██████████████                  | 223.9MB 5.0MB/s eta 0:00:58     |██████████████                  | 225.1MB 5.0MB/s eta 0:00:58     |██████████████▏                 | 225.7MB 5.0MB/s eta 0:00:57     |██████████████▎                 | 228.1MB 5.0MB/s eta 0:00:57     |██████████████▍                 | 229.4MB 5.0MB/s eta 0:00:57     |████████████████████████████▏   | 450.7MB 4.1MB/s eta 0:00:159    |██████████████▌                 | 231.2MB 5.0MB/s eta 0:00:56     |██████████████▋                 | 234.0MB 37.2MB/s eta 0:00:08     |██████████████▉                 | 236.3MB 37.2MB/s eta 0:00:08     |██████████████▉                 | 237.0MB 37.2MB/s eta 0:00:08     |███████████████                 | 238.3MB 37.2MB/s eta 0:00:08     |███████████████                 | 239.0MB 37.2MB/s eta 0:00:08     |███████████████                 | 240.7MB 37.2MB/s eta 0:00:08     |███████████████▏                | 242.0MB 37.2MB/s eta 0:00:08     |███████████████▏                | 243.2MB 37.2MB/s eta 0:00:08     |███████████████▎                | 245.1MB 4.3MB/s eta 0:01:03     |███████████████▍                | 245.6MB 4.3MB/s eta 0:01:03     |███████████████▍                | 247.0MB 4.3MB/s eta 0:01:02     |███████████████▌                | 247.6MB 4.3MB/s eta 0:01:02     |███████████████▋                | 250.1MB 4.3MB/s eta 0:01:02     |███████████████▉                | 252.5MB 4.3MB/s eta 0:01:01     |████████████████                | 254.6MB 4.3MB/s eta 0:01:01     |████████████████                | 255.8MB 4.4MB/s eta 0:00:58     |████████████████▎               | 260.9MB 4.4MB/s eta 0:00:57     |████████████████▍               | 261.5MB 4.4MB/s eta 0:00:57     |████████████████▌               | 263.3MB 4.4MB/s eta 0:00:57     |████████████████▋               | 265.1MB 4.4MB/s eta 0:00:56     |████████████████▋               | 265.6MB 12.5MB/s eta 0:00:20     |████████████████▊               | 266.7MB 12.5MB/s eta 0:00:20     |█████████████████▏              | 274.6MB 12.5MB/s eta 0:00:19     |█████████████████▍              | 278.4MB 12.5MB/s eta 0:00:19     |█████████████████▋              | 281.0MB 12.5MB/s eta 0:00:19     |█████████████████▋              | 282.4MB 12.5MB/s eta 0:00:19     |█████████████████▊              | 283.8MB 12.5MB/s eta 0:00:19     |██████████████████▏             | 290.0MB 5.9MB/s eta 0:00:38     |██████████████████▍             | 293.9MB 5.9MB/s eta 0:00:37     |██████████████████▌             | 295.3MB 5.9MB/s eta 0:00:37     |██████████████████▊             | 299.3MB 5.9MB/s eta 0:00:36     |███████████████████▏            | 306.2MB 5.9MB/s eta 0:00:35     |███████████████████▌            | 311.3MB 5.9MB/s eta 0:00:34     |███████████████████▌            | 312.6MB 4.4MB/s eta 0:00:46     |███████████████████▊            | 314.5MB 4.4MB/s eta 0:00:46     |████████████████████            | 319.7MB 4.4MB/s eta 0:00:45     |████████████████████            | 320.3MB 4.4MB/s eta 0:00:44     |████████████████████▏           | 321.6MB 4.4MB/s eta 0:00:44     |████████████████████▏           | 322.3MB 4.4MB/s eta 0:00:44     |████████████████████▎           | 323.6MB 4.7MB/s eta 0:00:40     |████████████████████▍           | 325.8MB 4.7MB/s eta 0:00:40     |████████████████████▌           | 327.1MB 4.7MB/s eta 0:00:40     |████████████████████▊           | 331.0MB 4.7MB/s eta 0:00:39     |████████████████████▊           | 332.2MB 4.7MB/s eta 0:00:39     |█████████████████████▏          | 338.6MB 4.5MB/s eta 0:00:39     |█████████████████████▍          | 341.2MB 4.5MB/s eta 0:00:39     |█████████████████████▍          | 341.7MB 4.5MB/s eta 0:00:38     |█████████████████████▌          | 344.0MB 4.5MB/s eta 0:00:38     |█████████████████████▌          | 344.5MB 4.5MB/s eta 0:00:38     |█████████████████████▊          | 347.7MB 4.0MB/s eta 0:00:41     |██████████████████████          | 353.5MB 4.0MB/s eta 0:00:40     |██████████████████████▏         | 355.2MB 4.0MB/s eta 0:00:40     |██████████████████████▎         | 355.8MB 4.0MB/s eta 0:00:39     |██████████████████████▎         | 356.4MB 4.0MB/s eta 0:00:39     |██████████████████████▎         | 356.9MB 4.0MB/s eta 0:00:39     |██████████████████████▍         | 357.5MB 4.0MB/s eta 0:00:39     |██████████████████████▍         | 358.1MB 4.6MB/s eta 0:00:34     |██████████████████████▌         | 359.9MB 4.6MB/s eta 0:00:33     |██████████████████████▋         | 361.6MB 4.6MB/s eta 0:00:33     |██████████████████████▊         | 362.9MB 4.6MB/s eta 0:00:33     |██████████████████████▊         | 364.1MB 4.6MB/s eta 0:00:32     |███████████████████████         | 366.6MB 4.6MB/s eta 0:00:32     |███████████████████████         | 369.1MB 3.7MB/s eta 0:00:39     |███████████████████████▏        | 369.7MB 3.7MB/s eta 0:00:39     |███████████████████████▏        | 370.3MB 3.7MB/s eta 0:00:38     |███████████████████████▎        | 372.2MB 3.7MB/s eta 0:00:38     |███████████████████████▍        | 373.4MB 3.7MB/s eta 0:00:38     |███████████████████████▍        | 374.6MB 3.7MB/s eta 0:00:37     |███████████████████████▋        | 377.0MB 3.7MB/s eta 0:00:37     |███████████████████████▊        | 378.7MB 3.7MB/s eta 0:00:36     |███████████████████████▊        | 379.3MB 3.7MB/s eta 0:00:36     |███████████████████████▉        | 380.4MB 4.2MB/s eta 0:00:32     |████████████████████████        | 382.1MB 4.2MB/s eta 0:00:31     |████████████████████████        | 383.2MB 4.2MB/s eta 0:00:31     |████████████████████████        | 383.8MB 4.2MB/s eta 0:00:31     |████████████████████████        | 384.3MB 4.2MB/s eta 0:00:31     |████████████████████████        | 384.9MB 4.2MB/s eta 0:00:30     |████████████████████████▏       | 386.4MB 4.2MB/s eta 0:00:30     |████████████████████████▎       | 387.4MB 4.2MB/s eta 0:00:30     |████████████████████████▎       | 388.1MB 4.2MB/s eta 0:00:30     |████████████████████████▍       | 389.3MB 4.2MB/s eta 0:00:29     |████████████████████████▍       | 389.9MB 3.9MB/s eta 0:00:32     |████████████████████████▌       | 391.2MB 3.9MB/s eta 0:00:31     |████████████████████████▌       | 392.4MB 3.9MB/s eta 0:00:31     |████████████████████████▋       | 394.3MB 3.9MB/s eta 0:00:31     |████████████████████████▊       | 396.1MB 3.9MB/s eta 0:00:30     |█████████████████████████       | 398.1MB 3.9MB/s eta 0:00:30     |█████████████████████████       | 399.3MB 3.9MB/s eta 0:00:29     |█████████████████████████       | 400.0MB 3.9MB/s eta 0:00:29     |█████████████████████████▎      | 404.4MB 4.3MB/s eta 0:00:26     |█████████████████████████▍      | 405.1MB 4.3MB/s eta 0:00:25     |█████████████████████████▌      | 408.2MB 4.3MB/s eta 0:00:25     |█████████████████████████▉      | 412.7MB 4.3MB/s eta 0:00:24     |██████████████████████████      | 414.6MB 5.2MB/s eta 0:00:19     |██████████████████████████      | 415.8MB 5.2MB/s eta 0:00:19     |██████████████████████████      | 417.0MB 5.2MB/s eta 0:00:19     |██████████████████████████▎     | 420.7MB 5.2MB/s eta 0:00:18     |██████████████████████████▍     | 421.8MB 5.2MB/s eta 0:00:18     |██████████████████████████▌     | 423.5MB 5.2MB/s eta 0:00:17     |██████████████████████████▌     | 424.6MB 5.2MB/s eta 0:00:17     |██████████████████████████▋     | 425.2MB 3.5MB/s eta 0:00:25     |██████████████████████████▋     | 426.3MB 3.5MB/s eta 0:00:25     |██████████████████████████▊     | 427.9MB 3.5MB/s eta 0:00:24     |███████████████████████████     | 431.3MB 3.5MB/s eta 0:00:23     |███████████████████████████     | 431.7MB 3.5MB/s eta 0:00:23     |███████████████████████████     | 432.4MB 3.5MB/s eta 0:00:23     |███████████████████████████     | 433.3MB 3.5MB/s eta 0:00:23     |███████████████████████████▏    | 433.8MB 6.7MB/s eta 0:00:12   | 434.2MB 6.7MB/s eta 0:00:12████████████████████▏    | 434.5MB 6.7MB/s eta 0:00:12    | 434.8MB 6.7MB/s eta 0:00:12�████████████████████▏    | 435.1MB 6.7MB/s eta 0:00:12     |███████████████████████████▎    | 436.8MB 6.7MB/s eta 0:00:12   | 438.4MB 6.7MB/s eta 0:00:11 439.2MB 6.7MB/s eta 0:00:11     |███████████████████████████▋    | 440.6MB 4.1MB/s eta 0:00:18     |███████████████████████████▋    | 442.3MB 4.1MB/s eta 0:00:18     |███████████████████████████▊    | 444.0MB 4.1MB/s eta 0:00:17     |███████████████████████████▉    | 445.0MB 4.1MB/s eta 0:00:17     |████████████████████████████    | 446.2MB 4.1MB/s eta 0:00:17     |████████████████████████████    | 448.1MB 4.1MB/s eta 0:00:16     |████████████████████████████    | 449.5MB 4.1MB/s eta 0:00:16     |████████████████████████████▏   | 450.1MB 4.1MB/s eta 0:00:16     |████████████████████████████████| 511.7MB 13.2MB/s eta 0:00:01    |████████████████████████████▍   | 453.5MB 5.5MB/s eta 0:00:11     |████████████████████████████▍   | 454.7MB 5.5MB/s eta 0:00:11     |████████████████████████████▌   | 455.9MB 5.5MB/s eta 0:00:11     |████████████████████████████▌   | 456.3MB 5.5MB/s eta 0:00:11     |████████████████████████████▊   | 458.5MB 5.5MB/s eta 0:00:10     |████████████████████████████▊   | 459.2MB 5.5MB/s eta 0:00:10     |████████████████████████████▉   | 460.9MB 14.4MB/s eta 0:00:04     |████████████████████████████▉   | 461.5MB 14.4MB/s eta 0:00:04     |█████████████████████████████   | 462.1MB 14.4MB/s eta 0:00:04     |█████████████████████████████   | 463.8MB 14.4MB/s eta 0:00:04     |█████████████████████████████▏  | 466.6MB 14.4MB/s eta 0:00:04     |█████████████████████████████▍  | 469.3MB 14.4MB/s eta 0:00:03     |█████████████████████████████▍  | 470.8MB 14.4MB/s eta 0:00:03     |█████████████████████████████▌  | 472.2MB 14.4MB/s eta 0:00:03     |█████████████████████████████▋  | 473.2MB 14.4MB/s eta 0:00:03�████████████████████████▋  | 473.4MB 14.4MB/s eta 0:00:03��█████▊  | 475.2MB 14.4MB/s eta 0:00:03��████████████████████████████▊  | 475.6MB 4.0MB/s eta 0:00:09�█████▊  | 475.9MB 4.0MB/s eta 0:00:09��█████████████████████████▉  | 476.2MB 4.0MB/s eta 0:00:09�██▉  | 476.5MB 4.0MB/s eta 0:00:09��████████████████████▉  | 476.8MB 4.0MB/s eta 0:00:09��████████████████████▉  | 477.1MB 4.0MB/s eta 0:00:09��████████████████████▉  | 477.3MB 4.0MB/s eta 0:00:09     |██████████████████████████████  | 478.4MB 4.0MB/s eta 0:00:09��████████  | 478.7MB 4.0MB/s eta 0:00:09     |██████████████████████████████▏ | 482.5MB 14.3MB/s eta 0:00:03     |██████████████████████████████▏ | 483.2MB 14.3MB/s eta 0:00:02     |██████████████████████████████▍ | 485.8MB 14.3MB/s eta 0:00:02     |██████████████████████████████▌ | 487.1MB 14.3MB/s eta 0:00:02     |██████████████████████████████▊ | 490.7MB 14.3MB/s eta 0:00:02     |██████████████████████████████▊ | 491.3MB 14.3MB/s eta 0:00:02     |██████████████████████████████▉ | 492.7MB 14.3MB/s eta 0:00:02     |███████████████████████████████ | 493.9MB 3.8MB/s eta 0:00:05     |███████████████████████████████ | 494.6MB 3.8MB/s eta 0:00:05     |███████████████████████████████ | 495.2MB 3.8MB/s eta 0:00:05     |███████████████████████████████ | 495.9MB 3.8MB/s eta 0:00:05     |███████████████████████████████ | 496.6MB 3.8MB/s eta 0:00:04     |███████████████████████████████ | 497.2MB 3.8MB/s eta 0:00:04     |███████████████████████████████▏| 497.9MB 3.8MB/s eta 0:00:04     |███████████████████████████████▋| 505.9MB 13.2MB/s eta 0:00:01     |███████████████████████████████▊| 507.8MB 13.2MB/s eta 0:00:01     |███████████████████████████████▉| 508.5MB 13.2MB/s eta 0:00:01     |███████████████████████████████▉| 509.1MB 13.2MB/s eta 0:00:01     |███████████████████████████████▉| 509.8MB 13.2MB/s eta 0:00:01     |████████████████████████████████| 510.5MB 13.2MB/s eta 0:00:01
Collecting numpy>=1.20
  Downloading https://files.pythonhosted.org/packages/6d/ad/ff3b21ebfe79a4d25b4a4f8e5cf9fd44a204adb6b33c09010f566f51027a/numpy-1.21.6-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (15.7MB)
     |████████████████████████████████| 15.7MB 26.7MB/s eta 0:00:01    |██▊                             | 1.4MB 26.7MB/s eta 0:00:01     |██████                          | 3.0MB 26.7MB/s eta 0:00:01     |████████████▍                   | 6.1MB 26.7MB/s eta 0:00:01     |█████████████████████           | 10.3MB 26.7MB/s eta 0:00:01
Collecting tensorflow-io-gcs-filesystem>=0.23.1
  Downloading https://files.pythonhosted.org/packages/02/e2/e52124db811cac83d1773efd3c1e456db3aedb7974a5a4c431126bc2da79/tensorflow_io_gcs_filesystem-0.26.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (2.4MB)
     |████████████████████████████████| 2.4MB 34.6MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (3.1.0)
Requirement already satisfied, skipping upgrade: google-pasta>=0.1.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.1.8)
Collecting astunparse>=1.6.0
  Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl
Collecting packaging
  Downloading https://files.pythonhosted.org/packages/05/8e/8de486cbd03baba4deef4142bd643a3e7bbe954a784dc1bb17142572d127/packaging-21.3-py3-none-any.whl (40kB)
     |████████████████████████████████| 40kB 40.7MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Requirement already satisfied, skipping upgrade: setuptools in /opt/conda/lib/python3.7/site-packages (from tensorflow) (41.4.0)
Collecting absl-py>=1.0.0
  Downloading https://files.pythonhosted.org/packages/11/8d/5fce604f03c8d30aa0d45451e67efe30d23e65eec7bbef9b9d341b86c0ef/absl_py-1.1.0-py3-none-any.whl (123kB)
     |████████████████████████████████| 133kB 28.8MB/s eta 0:00:01    |██████████████████▌             | 71kB 48.8MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: wrapt>=1.11.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.11.2)
Collecting protobuf<3.20,>=3.9.2
  Downloading https://files.pythonhosted.org/packages/03/6b/12b307892ef5e9f4a1a92f5996922561c453540f5ce22a09038d2486b451/protobuf-3.19.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1MB)
     |████████████████████████████████| 1.1MB 25.3MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: six>=1.12.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.12.0)
Requirement already satisfied, skipping upgrade: h5py>=2.9.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (2.9.0)
Requirement already satisfied, skipping upgrade: typing-extensions>=3.6.6 in /root/.local/lib/python3.7/site-packages (from tensorflow) (4.3.0)
Collecting libclang>=13.0.0
  Downloading https://files.pythonhosted.org/packages/ab/2f/c6f380aec0b064bccbd81141fecba9862b5634c838f13fff727adc84ceb9/libclang-14.0.1-py2.py3-none-manylinux1_x86_64.whl (14.5MB)
     |████████████████████████████████| 14.5MB 26.4MB/s eta 0:00:01    |███████████████████▏            | 8.7MB 26.4MB/s eta 0:00:01     |██████████████████████▎         | 10.1MB 26.4MB/s eta 0:00:01     |█████████████████████████▋      | 11.6MB 26.4MB/s eta 0:00:01     |████████████████████████████▉   | 13.0MB 26.4MB/s eta 0:00:01
Collecting keras-preprocessing>=1.1.1
  Downloading https://files.pythonhosted.org/packages/79/4c/7c3275a01e12ef9368a892926ab932b33bb13d55794881e3573482b378a7/Keras_Preprocessing-1.1.2-py2.py3-none-any.whl (42kB)
     |████████████████████████████████| 51kB 35.3MB/s eta 0:00:01
Collecting tensorflow-estimator<2.10.0,>=2.9.0rc0
  Downloading https://files.pythonhosted.org/packages/61/e1/a72ec68403d91ba433018db58859fd4706642aa9d0fb44ff778934fc4c2c/tensorflow_estimator-2.9.0-py2.py3-none-any.whl (438kB)
     |████████████████████████████████| 440kB 50.7MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: gast<=0.4.0,>=0.2.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.2.2)
Collecting grpcio<2.0,>=1.24.3
  Downloading https://files.pythonhosted.org/packages/6e/15/e6f3805d5003b894cce47af918c6419f2b27cec8d48722087005831203b4/grpcio-1.47.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.5MB)
     |████████████████████████████████| 4.5MB 9.6MB/s eta 0:00:01     |████████████▉                   | 1.8MB 9.6MB/s eta 0:00:01     |████████████████████████▎       | 3.4MB 9.6MB/s eta 0:00:01
Collecting tensorboard<2.10,>=2.9
  Downloading https://files.pythonhosted.org/packages/ee/0d/23812e6ce63b3d87c39bc9fee83e28c499052fa83fddddd7daea21a6d620/tensorboard-2.9.1-py3-none-any.whl (5.8MB)
     |████████████████████████████████| 5.8MB 15.2MB/s eta 0:00:01     |████████████████                | 2.9MB 15.2MB/s eta 0:00:01
Collecting flatbuffers<2,>=1.12
  Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Collecting keras<2.10.0,>=2.9.0rc0
  Downloading https://files.pythonhosted.org/packages/ff/ff/f25909606aed26981a8bd6d263f89d64a20ca5e5316e6aafb4c75d9ec8ae/keras-2.9.0-py2.py3-none-any.whl (1.6MB)
     |████████████████████████████████| 1.6MB 27.9MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: wheel<1.0,>=0.23.0 in /opt/conda/lib/python3.7/site-packages (from astunparse>=1.6.0->tensorflow) (0.33.6)
Requirement already satisfied, skipping upgrade: pyparsing!=3.0.5,>=2.0.2 in /opt/conda/lib/python3.7/site-packages (from packaging->tensorflow) (2.4.6)
Collecting google-auth-oauthlib<0.5,>=0.4.1
  Downloading https://files.pythonhosted.org/packages/b1/0e/0636cc1448a7abc444fb1b3a63655e294e0d2d49092dc3de05241be6d43c/google_auth_oauthlib-0.4.6-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (3.1.1)
Collecting google-auth<3,>=1.6.3
  Downloading https://files.pythonhosted.org/packages/42/1f/b3c5d018045df922f75a9acb81041ab0e2dbb37be8f6f354f0d28c01edea/google_auth-2.9.0-py2.py3-none-any.whl (167kB)
     |████████████████████████████████| 174kB 35.0MB/s eta 0:00:01
Collecting tensorboard-data-server<0.7.0,>=0.6.0
  Downloading https://files.pythonhosted.org/packages/60/f9/802efd84988bffd9f644c03b6e66fde8e76c3aa33db4279ddd11c5d61f4b/tensorboard_data_server-0.6.1-py3-none-manylinux2010_x86_64.whl (4.9MB)
     |████████████████████████████████| 4.9MB 28.1MB/s eta 0:00:01     |█████████████████████▊          | 3.3MB 28.1MB/s eta 0:00:01     |███████████████████████████████▋| 4.8MB 28.1MB/s eta 0:00:01
Collecting werkzeug>=1.0.1
  Downloading https://files.pythonhosted.org/packages/c4/44/f50f2d22cdfb6d56c03d1b4cc3cfa03ebee2f21b59a7768f151e43415ba5/Werkzeug-2.1.2-py3-none-any.whl (224kB)
     |████████████████████████████████| 225kB 39.1MB/s eta 0:00:01    |██████████▏                     | 71kB 53.4MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (2.22.0)
Collecting tensorboard-plugin-wit>=1.6.0
  Downloading https://files.pythonhosted.org/packages/e0/68/e8ecfac5dd594b676c23a7f07ea34c197d7d69b3313afdf8ac1b0a9905a2/tensorboard_plugin_wit-1.8.1-py3-none-any.whl (781kB)
     |████████████████████████████████| 788kB 34.6MB/s eta 0:00:01
Collecting requests-oauthlib>=0.7.0
  Downloading https://files.pythonhosted.org/packages/6f/bb/5deac77a9af870143c684ab46a7934038a53eb4aa975bc0687ed6ca2c610/requests_oauthlib-1.3.1-py2.py3-none-any.whl
Collecting cachetools<6.0,>=2.0.0
  Downloading https://files.pythonhosted.org/packages/68/aa/5fc646cae6e997c3adf3b0a7e257cda75cff21fcba15354dffd67789b7bb/cachetools-5.2.0-py3-none-any.whl
Collecting rsa<5,>=3.1.4; python_version >= "3.6"
  Downloading https://files.pythonhosted.org/packages/30/ab/8fd9e88e6fa5ec41afca995938bbefb72195278e0cfc5bd76a4f29b23fb2/rsa-4.8-py3-none-any.whl
Collecting pyasn1-modules>=0.2.1
  Downloading https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl (155kB)
     |████████████████████████████████| 163kB 59.1MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (1.24.2)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2.8)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2019.11.28)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (3.0.4)
Collecting oauthlib>=3.0.0
  Downloading https://files.pythonhosted.org/packages/1d/46/5ee2475e1b46a26ca0fa10d3c1d479577fde6ee289f8c6aa6d7ec33e31fd/oauthlib-3.2.0-py3-none-any.whl (151kB)
     |████████████████████████████████| 153kB 58.6MB/s eta 0:00:01
Collecting pyasn1>=0.1.3
  Downloading https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl (77kB)
     |████████████████████████████████| 81kB 55.4MB/s eta 0:00:01
Installing collected packages: numpy, tensorflow-io-gcs-filesystem, astunparse, packaging, absl-py, protobuf, libclang, keras-preprocessing, tensorflow-estimator, grpcio, cachetools, pyasn1, rsa, pyasn1-modules, google-auth, oauthlib, requests-oauthlib, google-auth-oauthlib, tensorboard-data-server, werkzeug, tensorboard-plugin-wit, tensorboard, flatbuffers, keras, tensorflow
  WARNING: The scripts f2py, f2py3 and f2py3.7 are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  Found existing installation: protobuf 4.21.2
    Uninstalling protobuf-4.21.2:
      Successfully uninstalled protobuf-4.21.2
  WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script google-oauthlib-tool is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed absl-py-1.1.0 astunparse-1.6.3 cachetools-5.2.0 flatbuffers-1.12 google-auth-2.9.0 google-auth-oauthlib-0.4.6 grpcio-1.47.0 keras-2.9.0 keras-preprocessing-1.1.2 libclang-14.0.1 numpy-1.21.6 oauthlib-3.2.0 packaging-21.3 protobuf-3.19.4 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-oauthlib-1.3.1 rsa-4.8 tensorboard-2.9.1 tensorboard-data-server-0.6.1 tensorboard-plugin-wit-1.8.1 tensorflow-2.9.1 tensorflow-estimator-2.9.0 tensorflow-io-gcs-filesystem-0.26.0 werkzeug-2.1.2
Note: you may need to restart the kernel to use updated packages.

After the above installations have finished be sure to restart the kernel. You can do this by going to Kernel > Restart.

In [1]:
# Import TensorFlow 
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub

# Ignore some warnings that are not relevant (you can remove this if you prefer)
import warnings
warnings.filterwarnings('ignore')
In [2]:
# TODO: Make all necessary imports.
import warnings
warnings.filterwarnings('ignore')

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import json

import tensorflow as tf
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
In [3]:
# Some other recommended settings:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [4]:
# TODO: Load the dataset with TensorFlow Datasets.
dataset, dataset_info = tfds.load('oxford_flowers102', as_supervised = True, with_info = True)
# TODO: Create a training set, a validation set and a test set.
train = dataset['train']
test = dataset["test"]
validation = dataset["validation"]
In [5]:
print('dataset has type:', type(dataset))
dataset has type: <class 'dict'>

Explore the Dataset

In [6]:
# TODO: Get the number of examples in each set from the dataset info.
splits_names = ['train', 'test', 'validation']
for s in splits_names:
    print('The split {} has {} records'.format(s, dataset_info.splits[s].num_examples))
    
total_num_examples = dataset_info.splits['train'].num_examples

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes
print("Number of Classes is: ", num_classes)
The split train has 1020 records
The split test has 6149 records
The split validation has 1020 records
Number of Classes is:  102
In [16]:
# TODO: Print the shape and corresponding label of 5 images in the training set.
for image, label in training_set.take(5):
    image = image.numpy()
    label = label.numpy()

    plt.imshow(image)
    plt.show()

    print('The shape of this image is:', image.shape)
    print('The label of this image is:', label)
The shape of this image is: (500, 667, 3)
The label of this image is: 72
The shape of this image is: (500, 666, 3)
The label of this image is: 84
The shape of this image is: (670, 500, 3)
The label of this image is: 70
The shape of this image is: (500, 505, 3)
The label of this image is: 51
The shape of this image is: (500, 672, 3)
The label of this image is: 48
In [8]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
i = 1
for image, label in train.take(3):
    print('The image',i, 'in the training set has:\n\u2022 shape is:', image.shape,'\n\u2022 label is:',label.numpy())
    i =i+1
The image 1 in the training set has:
• shape is: (500, 667, 3) 
• label is: 72
The image 2 in the training set has:
• shape is: (500, 666, 3) 
• label is: 84
The image 3 in the training set has:
• shape is: (670, 500, 3) 
• label is: 70
In [9]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding image label. 
for im, label in train.take(1):
    im = im.numpy().squeeze()
    label = label.numpy()
    plt.imshow(im, cmap= plt.cm.binary)
    plt.title(label)
    plt.colorbar()
    plt.show()

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [11]:
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
    
class_names
Out[11]:
{'21': 'fire lily',
 '3': 'canterbury bells',
 '45': 'bolero deep blue',
 '1': 'pink primrose',
 '34': 'mexican aster',
 '27': 'prince of wales feathers',
 '7': 'moon orchid',
 '16': 'globe-flower',
 '25': 'grape hyacinth',
 '26': 'corn poppy',
 '79': 'toad lily',
 '39': 'siam tulip',
 '24': 'red ginger',
 '67': 'spring crocus',
 '35': 'alpine sea holly',
 '32': 'garden phlox',
 '10': 'globe thistle',
 '6': 'tiger lily',
 '93': 'ball moss',
 '33': 'love in the mist',
 '9': 'monkshood',
 '102': 'blackberry lily',
 '14': 'spear thistle',
 '19': 'balloon flower',
 '100': 'blanket flower',
 '13': 'king protea',
 '49': 'oxeye daisy',
 '15': 'yellow iris',
 '61': 'cautleya spicata',
 '31': 'carnation',
 '64': 'silverbush',
 '68': 'bearded iris',
 '63': 'black-eyed susan',
 '69': 'windflower',
 '62': 'japanese anemone',
 '20': 'giant white arum lily',
 '38': 'great masterwort',
 '4': 'sweet pea',
 '86': 'tree mallow',
 '101': 'trumpet creeper',
 '42': 'daffodil',
 '22': 'pincushion flower',
 '2': 'hard-leaved pocket orchid',
 '54': 'sunflower',
 '66': 'osteospermum',
 '70': 'tree poppy',
 '85': 'desert-rose',
 '99': 'bromelia',
 '87': 'magnolia',
 '5': 'english marigold',
 '92': 'bee balm',
 '28': 'stemless gentian',
 '97': 'mallow',
 '57': 'gaura',
 '40': 'lenten rose',
 '47': 'marigold',
 '59': 'orange dahlia',
 '48': 'buttercup',
 '55': 'pelargonium',
 '36': 'ruby-lipped cattleya',
 '91': 'hippeastrum',
 '29': 'artichoke',
 '71': 'gazania',
 '90': 'canna lily',
 '18': 'peruvian lily',
 '98': 'mexican petunia',
 '8': 'bird of paradise',
 '30': 'sweet william',
 '17': 'purple coneflower',
 '52': 'wild pansy',
 '84': 'columbine',
 '12': "colt's foot",
 '11': 'snapdragon',
 '96': 'camellia',
 '23': 'fritillary',
 '50': 'common dandelion',
 '44': 'poinsettia',
 '53': 'primula',
 '72': 'azalea',
 '65': 'californian poppy',
 '80': 'anthurium',
 '76': 'morning glory',
 '37': 'cape flower',
 '56': 'bishop of llandaff',
 '60': 'pink-yellow dahlia',
 '82': 'clematis',
 '58': 'geranium',
 '75': 'thorn apple',
 '41': 'barbeton daisy',
 '95': 'bougainvillea',
 '43': 'sword lily',
 '83': 'hibiscus',
 '78': 'lotus lotus',
 '88': 'cyclamen',
 '94': 'foxglove',
 '81': 'frangipani',
 '74': 'rose',
 '89': 'watercress',
 '73': 'water lily',
 '46': 'wallflower',
 '77': 'passion flower',
 '51': 'petunia'}
In [12]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 

for im, label in train.take(1):
    im = im.numpy().squeeze()
    label = str(label.numpy())
    plt.imshow(im, cmap= plt.cm.binary)
    plt.title(class_names[label])
    plt.colorbar()
    plt.show()

Create Pipeline

In [14]:
# TODO: Create a pipeline for each set.
def normalize(image, label):
    image = tf.image.resize(image, (224, 224))
    #image = tf.cast(image, tf.float32)
    image = (image / 255)
    return image, label

batch_size = 32

training_batches = train.cache().shuffle(dataset_info.splits.total_num_examples//4).map(normalize).batch(batch_size).prefetch(1)
testing_batches = test.cache().map(normalize).batch(batch_size).prefetch(1)
validation_batches = validation.cache().map(normalize).batch(batch_size).prefetch(1)
WARNING:tensorflow:AutoGraph could not transform <function normalize at 0x7f800d792cb0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function normalize at 0x7f800d792cb0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function normalize at 0x7f800d792cb0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
In [15]:
training_batches.take(2)
Out[15]:
<TakeDataset element_spec=(TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name=None), TensorSpec(shape=(None,), dtype=tf.int64, name=None))>
In [16]:
for image_batch, label_batch in training_batches.take(1):
    print("The image shape of batch is: ", image_batch.shape)
    print("The label of batch shape is: ", label_batch.shape)
The image shape of batch is:  (32, 224, 224, 3)
The label of batch shape is:  (32,)

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [17]:
# TODO: Build and train your network.

import tensorflow_hub as hub
from tensorflow.keras import layers


classifier_url ="https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4" #@param {type:"string"}
img_shape = (224, 224)

classifier = tf.keras.Sequential([
    hub.KerasLayer(classifier_url, input_shape=img_shape+(3,))])

classifier.trainable = False

model = tf.keras.Sequential([
  classifier,
  tf.keras.layers.Dense(102, activation='softmax')])

model.summary()
WARNING:tensorflow:AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7f806c245f90>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7f806c245f90>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7f806c245f90>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 sequential (Sequential)     (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 102)               130662    
                                                                 
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________
In [18]:
print('Is there a GPU Available:', tf.test.is_gpu_available())

model.compile(optimizer='adam',
  loss='sparse_categorical_crossentropy',
  metrics=['accuracy'])

if tf.test.is_gpu_available():
    early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=3)
    old = model.fit(training_batches,
                        epochs = 20,
                        validation_data = validation_batches,
                        callbacks = [early_stopping])
else:
    old = model.fit(training_batches,
                        epochs = 5,
                        validation_data = validation_batches)
WARNING:tensorflow:From <ipython-input-18-7dd311f1cb26>:1: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
WARNING:tensorflow:From <ipython-input-18-7dd311f1cb26>:1: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
Is there a GPU Available: False
Epoch 1/5
WARNING:tensorflow:AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x7f800cdc4050> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x7f800cdc4050> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x7f800cdc4050> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
32/32 [==============================] - ETA: 0s - loss: 4.1780 - accuracy: 0.1157WARNING:tensorflow:AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x7f800798f170> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x7f800798f170> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x7f800798f170> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
32/32 [==============================] - 98s 3s/step - loss: 4.1780 - accuracy: 0.1157 - val_loss: 2.9616 - val_accuracy: 0.4382
Epoch 2/5
32/32 [==============================] - 89s 3s/step - loss: 2.0295 - accuracy: 0.6961 - val_loss: 1.9363 - val_accuracy: 0.6647
Epoch 3/5
32/32 [==============================] - 89s 3s/step - loss: 1.0858 - accuracy: 0.8990 - val_loss: 1.4862 - val_accuracy: 0.7441
Epoch 4/5
32/32 [==============================] - 88s 3s/step - loss: 0.6677 - accuracy: 0.9569 - val_loss: 1.2563 - val_accuracy: 0.7706
Epoch 5/5
32/32 [==============================] - 89s 3s/step - loss: 0.4413 - accuracy: 0.9775 - val_loss: 1.1238 - val_accuracy: 0.7941
In [19]:
# Checking how the accuracy improves
prior_data = pd.DataFrame(old.history)
print(prior_data)
       loss  accuracy  val_loss  val_accuracy
0  4.178005  0.115686  2.961571      0.438235
1  2.029480  0.696078  1.936328      0.664706
2  1.085765  0.899020  1.486197      0.744118
3  0.667747  0.956863  1.256268      0.770588
4  0.441341  0.977451  1.123756      0.794118
In [20]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.

fig, ax = plt.subplots(ncols=2, figsize=(16,10))
ax[0].plot(prior_data[["loss"]], 'g', label="Training Loss")
ax[0].plot(prior_data[["val_loss"]], 'r', label="Validation Loss")
ax[0].legend()

ax[1].plot(prior_data[["accuracy"]],'g', label="Training Accuracy")
ax[1].plot(prior_data[["val_accuracy"]], 'r', label="Validation Accuracy")
ax[1].legend()
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [21]:
# TODO: Print the loss and accuracy values achieved on the entire test set.

tested_network = model.evaluate(testing_batches)

print(tested_network)
193/193 [==============================] - 299s 2s/step - loss: 1.2763 - accuracy: 0.7497
[1.276318073272705, 0.7497153878211975]

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [23]:
# TODO: Saving the trained model as a Keras model.

import datetime
import os
import sys

p2date = datetime.date.today().strftime("%Y_%h_%d")
fname = 'raghavp1.h5'
In [24]:
model.save(fname, save_format = 'HDF5')

Load the Keras Model

Load the Keras model you saved above.

In [25]:
# TODO: Loading the Keras model


modelnow = tf.keras.models.load_model("./raghavp1.h5", custom_objects={'KerasLayer':hub.KerasLayer})
In [27]:
loaded_model.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer_2 (KerasLayer)  (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 102)               130662    
                                                                 
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [26]:
# TODO: Creating the process_image function

def processing_image(test_image):
    processed_image = np.squeeze(test_image)
    processed_image = tf.image.resize(processed_image, (224, 224))
    processed_image /= 255
    
    return processed_image

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [28]:
#outputting image
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = processing_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('original_image')
ax2.imshow(processed_test_image)
ax2.set_title('processed_image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [44]:
# TODO: Creating the predict function

def predicting(image_path, model, K, cls_names = class_names):
    im = Image.open(image_path)
    prediction_image = np.asarray(im)
    prediction_image = processing_image(prediction_image)
    
    prediction = model.predict(np.expand_dims(prediction_image, 0))

    r_df = pd.DataFrame(predicting[0]).reset_index().rename(columns = {'index': 'class_code',0: 'prob'})\
                        .sort_values(by='prob', ascending = False).head(K).reset_index(drop=True)
    r_df.loc[:,'class_code'] = r_df.class_code + 1
    r_df.loc[:,'class_name'] = np.nan

    for code in r_df['class_code'].values:
        class_name = cls_names[str(code)]
        r_df.loc[:,'class_name'] = np.where(r_df.class_code == code, class_name, r_df.class_name)
    
    return r_df, prediction_image
In [46]:
# TODO: Create the predict function

def predict(image_path, model, K, cls_names = class_names):
    im = Image.open(image_path)
    prediction_image = np.asarray(im)
    prediction_image = processing_image(prediction_image)
    
    prediction = model.predict(np.expand_dims(prediction_image, 0))

    r_df = pd.DataFrame(prediction[0]).reset_index().rename(columns = {'index': 'class_code',0: 'prob'})\
                        .sort_values(by='prob', ascending = False).head(K).reset_index(drop=True)
    r_df.loc[:,'class_code'] = r_df.class_code + 1
    r_df.loc[:,'class_name'] = np.nan

    for code in r_df['class_code'].values:
        class_name = cls_names[str(code)]
        r_df.loc[:,'class_name'] = np.where(r_df.class_code == code, class_name, r_df.class_name)
    
    return r_df, prediction_image

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [47]:
# TODO: Plotting the input image along with the top 5 classes


import glob

files = glob.glob('./test_images/*')

for file in files:
    if file.endswith('.jpg'):
        flower = file.split('/')[len(file.split('/'))-1][:-4]
        req = predict(file, model, 5)
        fig, (ax1, ax2) = plt.subplots(figsize=(10,5), ncols=2)
        ax1.imshow(req[1])
        ax1.set_title('input-image: {}'.format(flower))
        ax2.barh(req[0].class_name, req[0].prob)
        ax2.set_title('predict-probability')
        plt.tight_layout()
        plt.show()
WARNING:tensorflow:AutoGraph could not transform <function Model.make_predict_function.<locals>.predict_function at 0x7f8005ca7290> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function Model.make_predict_function.<locals>.predict_function at 0x7f8005ca7290> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <function Model.make_predict_function.<locals>.predict_function at 0x7f8005ca7290> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
1/1 [==============================] - 2s 2s/step
1/1 [==============================] - 0s 62ms/step
1/1 [==============================] - 0s 55ms/step
1/1 [==============================] - 0s 61ms/step
In [ ]: